<template>
  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}">
    <a-form-item label="创建类型" v-bind="validateInfos.type">
      <a-radio-group v-model:value="modelRef.type" button-style="solid">
        <a-radio-button value="folder">
          <FolderOpenOutlined />文件夹</a-radio-button>
        <a-radio-button value="menu">
          <AppstoreOutlined />菜单项</a-radio-button>
      </a-radio-group>
    </a-form-item>
    <a-form-item label="名称" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" v-focus />
    </a-form-item>
    <a-form-item label="图标" v-bind="validateInfos.icon">
      <a-popover title="" trigger="click" placement="bottom">
        <template #content>
          <IconSelect @selected="selected" slot="content"></IconSelect>
        </template>
        <a-input v-model:value="modelRef.icon" placeholder="必选项" readOnly>
          <template #prefix>
            <component :is="modelRef.icon" />
          </template>
        </a-input>
      </a-popover>
    </a-form-item>
    <a-form-item label="所属文件夹" v-bind="validateInfos.parentCodePath">
      <a-cascader v-model:value="modelRef.parentCodePath" :options="treeData" :fieldNames="{label: 'name', value: 'code', children: 'children' }" changeOnSelect expandTrigger="hover">
        <template #displayRender="{labels, selectedOptions}">
          <span>{{labels[labels.length-1]}}</span>
        </template>
      </a-cascader>
    </a-form-item>
    <a-form-item label="访问地址" v-bind="validateInfos.path">
      <a-input v-model:value="modelRef.path"></a-input>
    </a-form-item>
    <a-form-item label="组件路径" v-bind="validateInfos.componentPath">
      <a-input v-model:value="modelRef.componentPath" />
    </a-form-item>
    <a-form-item label="组件名称" v-bind="validateInfos.componentName">
      <a-input v-model:value="modelRef.componentName" />
    </a-form-item>
    <a-form-item label="排序" v-bind="validateInfos.sort">
      <a-input-number v-model:value="modelRef.sort" :min="1" style="width:100%" />
    </a-form-item>
    <a-form-item label="重定向" v-if="modelRef.type == 'folder'">
      <a-tree-select v-model:value="modelRef.redirect" style="width: 100%" placeholder="请选择" :tree-data="treeSelectData" tree-node-filter-prop="name" :field-names="fieldNames">
        <template #title="{icon, name}">
          <span>
            <component :is="icon" />{{name}}</span>
        </template>
      </a-tree-select>
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
      <a-space>
        <a-button @click="resetFields">重置</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script>
import { insert, update, tree } from '@/api/sysMenuApi.ts'
import { defineComponent, reactive, toRefs, toRaw, onMounted } from 'vue'
import { Form, message } from 'ant-design-vue'
import IconSelect from '@/components/iconSelect/index.vue'
const useForm = Form.useForm
export default defineComponent({
  props: {
    type: String,
    row: Object
  },
  setup(props, context) {
    const { type, row } = props
    const data = reactive({
      treeData: [],
      treeSelectData: [],
      fieldNames: {
        children: 'children',
        label: 'name',
        value: 'finalPath'
      }
    })
    const modelRef = reactive({
      name: row?.name,
      path: row?.path,
      componentPath: row?.componentPath,
      componentName: row?.componentName,
      sort: row?.sort || 99,
      redirect: row?.redirect,
      type: row?.type || 'menu',
      icon: row?.icon || 'CrownFilled',
      parentCodePath: row?.parentCodePath?.split(',')
    })
    const rulesRef = reactive({
      icon: [
        {
          required: true,
          message: '图标必选项'
        }
      ],
      name: [
        {
          required: true,
          message: '菜单名称必填项'
        }
      ],
      parentCodePath: [
        {
          required: true,
          message: '上级菜单必填项'
        }
      ],
      sort: [
        {
          required: true,
          message: '排序必填项'
        }
      ],
      path: [
        {
          required: true,
          message: '访问地址必填项'
        }
      ],
      componentPath: [
        {
          required: true,
          message: '组件路径必填项'
        }
      ],
      componentName: [
        {
          required: true,
          message: '组件名称必填项'
        }
      ]
    })
    const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef)

    const onSubmit = () => {
      validate()
        .then(() => {
          if (type == 'insert') {
            insertData()
          } else if (type == 'update') {
            updateData()
          }
        })
        .catch(err => {
          console.log('error', err)
        })
    }

    const initTreeData = () => {
      let params = {
        type: 'folder'
      }
      tree(params).then(resd => {
        if (row) {
          let currentCode = row.code

          let recursion = menuChild => {
            // 处理数据
            menuChild.map(menu => {
              // 判断 所选择的部门不能是当前部门和子部门
              if (menu.code == currentCode) menu.disabled = true
              if (menu.children) recursion(menu.children)
            })
          }
          // 处理数据
          recursion(resd)
        }

        data.treeData = [{ code: 'root', name: '根部门', children: resd }]
      })
    }

    const initTreeSelectData = () => {
      let params = {}
      tree(params).then(resd => {
        let currentCode = row?.code || ''

        let recursion = (menuChild, path) => {
          // 处理数据
          menuChild.map(menu => {
            menu.finalPath = path + '/' + menu.path
            // 判断 所选择的部门不能是当前部门和子部门
            if (row && menu.code == currentCode || menu.type=="folder") menu.disabled = true
            if (menu.children) recursion(menu.children, menu.finalPath)
          })
        }
        // 处理数据
        recursion(resd, '')

        data.treeSelectData = resd
      })
    }
    // 页面初始化
    onMounted(() => {
      initTreeData() // 初始化树
      initTreeSelectData() // 初始化下拉选项树
    })

    const insertData = () => {
      let form = toRaw(modelRef)
      let params = {
        name: form.name,
        icon: form.icon,
        type: form.type,
        parentCode: form.parentCodePath[form.parentCodePath.length - 1],
        parentCodePath: form.parentCodePath.join(','),
        path: form?.path,
        componentPath: form.componentPath,
        componentName: form.componentName,
        sort: form.sort || 99,
        redirect: form.type=="folder" ? form.redirect : ''
      }
      insert(params).then(resd => {
        message.success('创建成功')
        context.emit('success', resd)
      })
    }

    const updateData = () => {
      let form = toRaw(modelRef)
      let params = {
        id: row.id,
        name: form.name,
        icon: form.icon,
        type: form.type,
        parentCode: form.parentCodePath[form.parentCodePath.length - 1],
        parentCodePath: form.parentCodePath.join(','),
        path: form?.path,
        componentPath: form.componentPath,
        componentName: form.componentName,
        sort: form.sort || 99,
        redirect: form.type=="folder" ? form.redirect : ''
      }
      update(params).then(resd => {
        message.success('更新成功')
        context.emit('success', resd)
      })
    }

    const selected = icon => {
      modelRef.icon = icon
    }

    return {
      ...toRefs(data),
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
      selected
    }
  },
  components: {
    IconSelect
  }
})
</script>